﻿using System;
using System.Web;
using System.Xml;
using Agile.Crm4.Plugins.FilteredLookup.Properties;
using Microsoft.Crm.Sdk;

namespace Agile.Crm4.Plugins.FilteredLookup
{
    public class ExecutePlugin : IPlugin
    {

        /// <summary>
        /// This plugin should be registerd on pre-state Execute Message.
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IPluginExecutionContext context)
        {
            try
            {
                var validContext = IsExecuteFetchXmlContext(context);
                if (validContext == false)
                    return;

                var fetchxmlAdapter = new FetchXmlAdapter(context.InputParameters["FetchXml"] as string);
                                
                var filter = GetFilter(fetchxmlAdapter.EntityName);
                if (string.IsNullOrEmpty(filter))
                    return;
                
                context.InputParameters.Properties["FetchXml"] = fetchxmlAdapter.InjectFilter(filter).FetchXml;
            }

            //While it is bad practice to catch general exceptions, it is a neccassary evil in this context.
            //The "Execute" step is activated too many times to allow some unnoticed bug harm it. 
            //Either way, it is a good idea to attach a logging mechanism of some sort here.
            catch (Exception ex)
            {
                //TODO: add yor custom log here
            }
        }

     
        /// <summary>
        /// Get the matching filter
        /// </summary>
        /// <returns></returns>
        private static string GetFilter(string entityName)
        {
            var pageUrl = HttpContext.Current.Request.Url.ToString();
            var refererUrl = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
            var adapter = new AdditionalFilterAdapter(Settings.Default.FiltersKeyName, entityName, pageUrl, refererUrl);
            return adapter.GetAdditionalFilter();
        }

        /// <summary>
        /// Vaidates that the current message is Exceute of FetchXML request
        /// </summary>
        /// <param name="context"></param>
        /// <returns>true if message is Execute of FetchXml </returns>
        private static bool IsExecuteFetchXmlContext(IPluginExecutionContext context)
        {
            if (context.MessageName != "Execute")
                return false;

            if (context.InputParameters == null ||
                context.InputParameters.Properties == null ||
                context.InputParameters.Contains("FetchXml") == false)
                return false;

            return true;
        }

        
 
    }
}
